#include <linux/usb.h>
#include <linux/timer.h>
#include <asm/uaccess.h>
#include "yealink_w1dl.h"

////////////////////////////////////////////////////////////////////////////////////////////////////
//
// INIT PHONE
//

static void pkt_update_checksum(struct snd_packet *p, int len) {
	u8 *bp = (u8 *) p;
	u8 i, sum = 0;
	for (i = 0; i < len-1; i++)
		sum -= bp[i];
	bp[len-1] = sum;
}
static int create_lcd_packet(struct snd_packet *packet, u8 status, u8 writesize) {
	packet->cmd		= 0x05;
	packet->size	= 1;
	packet->offset	= 0;
	packet->data[0]	= status;
	packet->sum		= 0;
	pkt_update_checksum(packet, writesize);

	return 0;
}

static void yealink_write_int_callback(struct urb *urb) {
	struct usb_yealink *dev;
	int status = urb->status;

	info("callback in ...");
	
	dev = urb->context;

	/* sync/async unlink faults aren't errors */
	if (status) {
		if(!(status == -ENOENT || status == -ECONNRESET || status == -ESHUTDOWN))
			info("%s - nonzero write interrupt status received: %d", __func__, status);

		spin_lock(&dev->err_lock);
		dev->errors = status;
		spin_unlock(&dev->err_lock);
	}

	up(&dev->limit_sem);

	info("callback ok ...");
}
static void yealink_write_ctrl_callback(struct urb *urb) {
	struct usb_yealink *dev;
	int status = urb->status;

	info("callback ctrl ...");
	
	dev = urb->context;

	/* sync/async unlink faults aren't errors */
	if (status) {
		if(!(status == -ENOENT || status == -ECONNRESET || status == -ESHUTDOWN)) {
			switch (status) {
				case -EPROTO	: info("%s - failed callback write urb, error EPROTO", __func__); break;
				case -EILSEQ	: info("%s - failed callback write urb, error EILSEQ", __func__); break;
				case -EPIPE		: info("%s - failed callback write urb, error EPIPE", __func__); break;
				case -ETIMEDOUT	: info("%s - failed callback write urb, error ETIMEDOUT", __func__); break;
				case -ENODEV	: info("%s - failed callback write urb, error ENODEV", __func__); break;
				case -EREMOTEIO	: info("%s - failed callback write urb, error EREMOTEIO", __func__); break;
				case -EXDEV		: info("%s - failed callback write urb, error EXDEV", __func__); break;
				case -EINVAL	: info("%s - failed callback write urb, error EINVAL", __func__); break;
				case -EINPROGRESS	: info("%s - failed callback write urb, error EINPROGRESS", __func__); break;

				default			: info("%s - failed callback write urb, error %d", __func__, status); break;
			}
		}
		
		spin_lock(&dev->err_lock);
		dev->errors = status;
		spin_unlock(&dev->err_lock);
	} else
		info("callback ok ...");

	up(&dev->limit_sem);
}

static void free_urbs(struct usb_yealink *dev) {
	if (dev->int_urb) {
		usb_buffer_free(dev->udev, dev->writesize, dev->int_packet, dev->int_urb->transfer_dma);
		usb_free_urb(dev->int_urb);
	}

	if (dev->ctrl_urb) {
		usb_buffer_free(dev->udev, dev->writesize, dev->ctrl_packet, dev->ctrl_urb->transfer_dma);
		usb_buffer_free(dev->udev, sizeof( *(dev->ctrlrequest) ), dev->ctrlrequest, dev->ctrl_urb->setup_dma);
		usb_free_urb(dev->ctrl_urb);
	}
}
static int init_phone(struct usb_yealink *dev) {
	int retval = 0;

	/* limit the number of URBs in flight to stop a user from using up all RAM */
	if (down_interruptible(&dev->limit_sem)) {
		retval = -ERESTARTSYS;
		goto exit;
	}

	spin_lock_irq(&dev->err_lock);
	if ( (retval = dev->errors) < 0 ) {
		/* any error is reported once */
		dev->errors = 0;
		/* to preserve notifications about reset */
		retval = (retval == -EPIPE) ? retval : -EIO;
	}
	spin_unlock_irq(&dev->err_lock);
	
	if (retval < 0)
		goto error;

	//------------------------------------------------------------------------------------------------------------------------------------------
	info("init interrupt in urb");

	dev->int_urb = usb_alloc_urb(0, GFP_KERNEL);
	if (!dev->int_urb) {
		retval = -ENOMEM;
		goto error;
	}

	dev->int_pipe = usb_rcvintpipe(dev->udev, dev->int_endpointAddr);
	dev->writesize = usb_maxpacket(dev->udev, dev->int_pipe, usb_pipeout(dev->int_pipe));
	dev->int_packet = usb_buffer_alloc(dev->udev, dev->writesize, GFP_KERNEL, &dev->int_urb->transfer_dma);
	if (!dev->int_packet) {
		retval = -ENOMEM;
		goto error;
	}

	info("writesize is %d", dev->writesize);
	
	usb_fill_int_urb(dev->int_urb, dev->udev,
					dev->int_pipe, dev->int_packet,
					dev->writesize,
					yealink_write_int_callback, dev,
					dev->int_interval);

	dev->int_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
	dev->int_urb->dev = dev->udev;
	//------------------------------------------------------------------------------------------------------------------------------------------
	info("init control urb");

	dev->ctrl_urb = usb_alloc_urb(0, GFP_KERNEL);
	if (!dev->ctrl_urb) {
		retval = -ENOMEM;
		goto error;
	}

	dev->ctrl_pipe = usb_sndctrlpipe(dev->udev, 0);
	dev->ctrl_packet = usb_buffer_alloc(dev->udev, dev->writesize, GFP_KERNEL, &dev->ctrl_urb->transfer_dma);
	if (!dev->ctrl_packet) {
		retval = -ENOMEM;
		goto error;
	}

	dev->ctrlrequest = usb_buffer_alloc(dev->udev, sizeof( *(dev->ctrlrequest) ), GFP_KERNEL, &dev->ctrl_urb->setup_dma);
	if (!dev->ctrlrequest) {
		retval = -ENOMEM;
		goto error;
	}
	
	dev->ctrlrequest->bRequestType	= USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_OUT;
	dev->ctrlrequest->bRequest		= USB_REQ_SET_CONFIGURATION;
	dev->ctrlrequest->wValue		= cpu_to_le16(0x200);
	dev->ctrlrequest->wIndex		= cpu_to_le16(dev->number_end_points);
	dev->ctrlrequest->wLength		= cpu_to_le16(dev->writesize);

	usb_fill_control_urb(dev->ctrl_urb, dev->udev,
						dev->ctrl_pipe, (void *)dev->ctrlrequest,
						dev->ctrl_packet, dev->writesize,
						yealink_write_ctrl_callback, dev);
						
	dev->ctrl_urb->transfer_flags |= URB_NO_SETUP_DMA_MAP | URB_NO_TRANSFER_DMA_MAP;
	dev->ctrl_urb->dev = dev->udev;
	//------------------------------------------------------------------------------------------------------------------------------------------
	
	return 0;

error:
	free_urbs(dev);
	up(&dev->limit_sem);

exit:
	info("error init usb");
	
	return retval;
}

static void print_send_error(const int retval, const char *func_name) {
	switch (retval) {
		case -ENOMEM	: info("%s - failed submitting write urb, error ENOMEM", func_name); break;
		case -ENODEV	: info("%s - failed submitting write urb, error ENODEV", func_name); break;
		case -ENXIO		: info("%s - failed submitting write urb, error ENXIO", func_name); break;
		case -EINVAL	: info("%s - failed submitting write urb, error EINVAL", func_name); break;
		case -EAGAIN	: info("%s - failed submitting write urb, error EAGAIN", func_name); break;
		case -EFBIG		: info("%s - failed submitting write urb, error EFBIG", func_name); break;
		case -EPIPE		: info("%s - failed submitting write urb, error EPIPE", func_name); break;
		case -EMSGSIZE	: info("%s - failed submitting write urb, error EMSGSIZE", func_name); break;
		
		default			: info("%s - failed submitting write urb, error %d", func_name, retval); break;
	}
}
static size_t receive_data(struct usb_yealink *dev) {
	int retval = 0;
	struct urb *urb = dev->int_urb;
	
	usb_anchor_urb( urb, &dev->submitted );

	info("Submitting ...");
	
	/* this lock makes sure we don't submit URBs to gone devices */
	mutex_lock( &dev->io_mutex );
	if ( !dev->interface ) {		/* disconnect() was called */
		info("submit int urb: mutex lock error");
		mutex_unlock( &dev->io_mutex );
		retval = -ENODEV;
		goto error;
	}

	/* send the data out the interrupt port */
	retval = usb_submit_urb( urb, GFP_KERNEL );
	
	mutex_unlock(&dev->io_mutex);
	
	if (retval < 0) {
		print_send_error(retval, __func__);
		goto error_unanchor;
	}

	info("Submitted");

	return retval;
	
error_unanchor:
	usb_unanchor_urb( urb );
	
error:
	return retval;
}
static size_t send_command(struct usb_yealink *dev) {
	int retval = 0;
	struct snd_packet *packet = dev->ctrl_packet;

	info("Sending control message ...");
	
	/* this lock makes sure we don't send control message to gone devices */
	mutex_lock( &dev->io_mutex );
	if ( !dev->interface ) {		/* disconnect() was called */
		info("control msg: mutex lock error");
		mutex_unlock( &dev->io_mutex );
		retval = -ENODEV;
		goto error;
	}

	retval = usb_control_msg( dev->udev, dev->ctrl_pipe,
	 			USB_REQ_SET_CONFIGURATION, 
				USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_OUT, 
				0x200, 3, packet, sizeof( *packet ), USB_CTRL_SET_TIMEOUT );
	
	mutex_unlock(&dev->io_mutex);
	
	if (retval < 0) {
		print_send_error(retval, __func__);
		goto error;
	}

	info("Sended");

error:
	return retval;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// REGISTER/UNREGISTER MODULE
//

static void yealink_delete(struct kref *kref) {
	struct usb_yealink *dev = to_yealink_dev(kref);

	usb_put_dev(dev->udev);
	kfree(dev->int_buffer);
	kfree(dev);
}
static int yealink_probe(struct usb_interface *interface, const struct usb_device_id *id) {
	struct usb_yealink *dev;
	struct usb_host_interface *iface_desc;
	struct usb_endpoint_descriptor *endpoint;
	size_t buffer_size;
	int i;
	int retval = -ENOMEM;

	info("** Probing Yealink W1DL **");
	
	info("Allocating memory ...");
	
	/* allocate memory for our device state and initialize it */
	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
	if (!dev) {
		info("Out of memory");
		goto error;
	}
	
	info("Initializing dev struct ...");
	
	kref_init(&dev->kref);
	sema_init(&dev->limit_sem, WRITES_IN_FLIGHT);
	mutex_init(&dev->io_mutex);
	spin_lock_init(&dev->err_lock);
	init_usb_anchor(&dev->submitted);

	info("Getting usb device ...");
	
	dev->udev = usb_get_dev( interface_to_usbdev(interface) );
	dev->interface = interface;

	info("The number of alternate settings is %d", interface->num_altsetting);

	info("Finding interrupt endpoint ...");
	
	/* set up the endpoint information */
	/* use only the first interrupt interrupt endpoint */
	iface_desc = interface->cur_altsetting;
	dev->number_end_points = iface_desc->desc.bNumEndpoints;
	info("Endpoints amount: %d", iface_desc->desc.bNumEndpoints);
	info("Interface number is %d", iface_desc->desc.bInterfaceNumber);
	
	for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
		info("Endpoint #%d, start", i);

		endpoint = &iface_desc->endpoint[i].desc;

		info("Endpoint #%d, checking in", i);

		if (!dev->int_endpointAddr && usb_endpoint_is_int_in(endpoint)) {
			info("Interrupt endpoint has been founded ...");

			/* we found a interrupt in endpoint */
			buffer_size = le16_to_cpu(endpoint->wMaxPacketSize);
			dev->int_interval = endpoint->bInterval;
			dev->int_size = buffer_size;
			dev->int_endpointAddr = endpoint->bEndpointAddress;
			dev->int_buffer = kmalloc(buffer_size, GFP_KERNEL);
			if (!dev->int_buffer) {
				info("Could not allocate int_buffer");
				goto error;
			}
		}

		info("Endpoint #%d, end", i);
	}
	if (!dev->int_endpointAddr) {
		info("Could not find interrupt endpoint");
		goto error;
	}

	info("Setting device data to interface ...");
	
	/* save our data pointer in this interface device */
	usb_set_intfdata(interface, dev);

	init_phone(dev);
	
	if ( create_lcd_packet(dev->ctrl_packet, 1, dev->writesize) ) {
		info("create packet failed");
		retval = -1000;
		goto error;
	}
	
	send_command(dev);

	info("Yealink W1DL now started");
	
	return 0;

error:
	if (dev)
		/* this frees allocated memory */
		kref_put(&dev->kref, yealink_delete);
	
	return retval;
}
static void yealink_disconnect(struct usb_interface *interface) {
	struct usb_yealink *dev;

	info("** Disconecting Yealink W1DL **");
	
	dev = usb_get_intfdata(interface);
	
	if ( create_lcd_packet(dev->ctrl_packet, 0, dev->writesize) ) {
		info("create packet failed");
	}
	
	send_command(dev);
	
	info("Killing URBs ...");
	free_urbs(dev);
	info("Killing anchored URBs ...");
	usb_kill_anchored_urbs(&dev->submitted);

	info("Deregistering Yealink W1DL ...");

	usb_set_intfdata(interface, NULL);

	info("Clearing interface ...");

	/* prevent more I/O from starting */
	mutex_lock(&dev->io_mutex);
	dev->interface = NULL;
	mutex_unlock(&dev->io_mutex);

	info("Freeing memory ...");

	/* decrement our usage count */
	kref_put(&dev->kref, yealink_delete);

	info("Yealink W1DL now disconnected");
}

////////////////////////////////////////////////////////////////////////////////////////////////////
//
// INIT/EXIT MODULE
//

static void yealink_draw_down(struct usb_yealink *dev) {
	int time;

	time = usb_wait_anchor_empty_timeout(&dev->submitted, 1000);
	if (!time)
		usb_kill_anchored_urbs(&dev->submitted);
}
static int yealink_suspend(struct usb_interface *intf, pm_message_t message) {
	struct usb_yealink *dev = usb_get_intfdata(intf);

	if (!dev)
		return 0;
	
	yealink_draw_down(dev);
	return 0;
}
static int yealink_resume (struct usb_interface *intf) {
	return 0;
}
static int yealink_pre_reset(struct usb_interface *intf) {
	struct usb_yealink *dev = usb_get_intfdata(intf);

	mutex_lock(&dev->io_mutex);
	yealink_draw_down(dev);

	return 0;
}
static int yealink_post_reset(struct usb_interface *intf) {
	struct usb_yealink *dev = usb_get_intfdata(intf);

	/* we are sure no URBs are active - no locking needed */
	dev->errors = -EPIPE;
	mutex_unlock(&dev->io_mutex);

	return 0;
}

static struct usb_device_id yealink_table [] = {
	{ USB_DEVICE_AND_INTERFACE_INFO(VENDOR_ID, PRODUCT_ID, USB_CLASS_HID, IFACE_SUBCLASS, IFACE_PROTOCOL) },
	{ }
};
MODULE_DEVICE_TABLE(usb, yealink_table);

static struct usb_driver yealink_driver = {
	.name		= YEALINK_DEV_NAME,
	.probe		= yealink_probe,
	.disconnect	= yealink_disconnect,
	.suspend    = yealink_suspend,
	.resume     = yealink_resume,
	.pre_reset  = yealink_pre_reset,
	.post_reset = yealink_post_reset,
	.id_table   = yealink_table,
	.supports_autosuspend = 1,
};

static int __init yealink_module_init(void) {
	int result;

	result = usb_register(&yealink_driver);
	if (result)
		info("usb_register failed. Error number %d", result);

	return result;
}
static void __exit yealink_module_exit(void) {
	usb_deregister(&yealink_driver);
}

module_init(yealink_module_init);
module_exit(yealink_module_exit);

MODULE_LICENSE("GPL");
